package com.behelpful.common.integration.iredis.support;

import com.behelpful.common.integration.iredis.annotation.ThreadJedis;
import com.behelpful.common.integration.iredis.annotation.ThreadShardJedis;
import lombok.AllArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author Alay
 * @date 2021-05-06 12:09
 * @project behelpful
 */
@Aspect
@Component
@AllArgsConstructor
public class IRedisAspect {

    private final IRedisUtil iRedisUtil;

    @Pointcut("@annotation(threadJedis)")
    public void pointCut(ThreadJedis threadJedis) {
    }


    @Around("pointCut(threadJedis)")
    public Object redisAround(ProceedingJoinPoint point, ThreadJedis threadJedis) throws Throwable {
        Object result;
        try {
            // 调用目标方法
            result = point.proceed();
        } catch (Throwable throwable) {
            // 异常通知
            throwable.printStackTrace();
            throw throwable;
        } finally {
            // 后置通知
            iRedisUtil.closeJedis();
        }
        // 返回通知
        return result;
    }

    @Around("@annotation(threadShardJedis)")
    public Object redisAround(ProceedingJoinPoint point, ThreadShardJedis threadShardJedis) throws Throwable {
        Object result;
        try {
            // 调用目标方法
            result = point.proceed();
        } catch (Throwable throwable) {
            // 异常通知
            throwable.printStackTrace();
            throw throwable;
        } finally {
            // 后置通知
            iRedisUtil.closeShardJedis();
        }
        // 返回通知
        return result;
    }
}